package cn.edu.hrbcu.es.invigilatemanagerment.configuration;

import cn.edu.hrbcu.es.invigilatemanagerment.dao.PermissionMapper;
import cn.edu.hrbcu.es.invigilatemanagerment.dao.RoleMapper;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Permission;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Role;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PermissionFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        Set<ConfigAttribute> set = new HashSet<>();
        // 获取请求地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //将?后的内容去掉（发送get请求时会携带参数）
        String cleanUrl = requestUrl.split("\\?")[0];
        log.info("requestUrl >> {}", requestUrl);
        if("/ExamInfo/queryAllExamInfoForStudent".equals(requestUrl))
            return SecurityConfig.createList("ROLE_LOGIN");
        if("/ExamInfo/toQueryAllExamInfoForStudent".equals(requestUrl))
            return SecurityConfig.createList("ROLE_LOGIN");
        //查询数据库中所有资源
        List<Permission> allPermissions = permissionMapper.findAllPermissions();
        if (!CollectionUtils.isEmpty(allPermissions)) {
            List<String> urlList = allPermissions.stream()
                    .filter(f->f.getUrl().endsWith("**")
                            ?cleanUrl.startsWith(f.getUrl().substring(0,f.getUrl().lastIndexOf("/")))
                            :cleanUrl.equals(f.getUrl()))
                    .map(permission -> permission.getUrl())
                    .collect(Collectors.toList());
            System.out.println("cleanUrl"+cleanUrl+"");
            for (String url:urlList){
                List<Role> roles = roleMapper.findRolesByUrl(url); //当前请求需要的权限
                if(!CollectionUtils.isEmpty(roles)){
                    roles.forEach(role -> {
                        SecurityConfig securityConfig = new SecurityConfig(role.getAuthority());
                        set.add(securityConfig);
                    });
                }
            }
        }
        if (ObjectUtils.isEmpty(set)) {
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        return set;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
